<template>
  <view class="page">
    <view v-if="$data.info">
      <!-- 地址 -->
      <view class="address" @tap="onCheckAddress">
        <view class="address_left">
          {{ $data.address || "请选择服务地址" }}
        </view>
        <view class="address_right">
          <image :src="ImgIconRightGray" />
        </view>
      </view>
      <!-- 产品详情 -->
      <view class="detail">
        <view class="detail_img">
          <image :src="$data.info._picurl" />
        </view>
        <view class="detail_content">
          <view class="detail_content--title">
            {{ $data.info.serviceTitle }}
          </view>
          <view class="detail_content--desc">
            已选：
            {{ $data.info.serviceTitle }}
          </view>
          <view class="detail_content--price text-price">
            {{ $data.info.totalPrice }}
          </view>
        </view>
      </view>
      <!-- 服务时间 -->
      <view class="time">
        <view class="time_title">服务时间</view>
        <view class="time_content" @tap="() => ($data.chooseTimeShow = true)">
          <view class="time_content--check">
            <text v-if="$data.time" class="text-main-color">
              {{ $data.time }}
            </text>
            <text v-else class="text-gray">请添加服务时间</text>
          </view>
          <view class="time_content--icon">
            <image :src="ImgIconRightGray" />
          </view>
        </view>
      </view>
      <!-- 备注 -->
      <view class="card margin-top">
        <view class="card_title margin-bottom">备注</view>
        <up-textarea
          v-model="params.remark"
          placeholder="如有其他要求请备注"
          :height="100"
          :maxlength="150"
          border="surround"
          count
        ></up-textarea>
      </view>
      <!-- 底部结算按钮 -->
      <view class="foot foot_box">
        <view class="btn btn_cancel" @tap="onBack">返回</view>
        <view class="btn btn_save" @tap="onSave">预约</view>
      </view>
    </view>
    <PopupChooseTime
      v-model:show="$data.chooseTimeShow"
      :nowDay="$data.nowDate"
      @confirm="onChooseTime"
    />
    <PopupLogin />
  </view>
</template>
  
<script setup>
import { getCurrentInstance, reactive, ref, nextTick } from "vue";
import { onLoad, onShow, onReady, onUnload } from "@dcloudio/uni-app";
import BasicConfig from "@/utils/config";
import { eventBus } from "../../../enums/eventBus";
import { skuInputType } from "../../../enums/sku";
import { useGetLocationStorage } from "../../../hooks/useStorage";
import {
  freePay,
  getOrderDetail,
  orderConfirm,
  orderImmediate,
  updateSubscribeOrder,
} from "../../../api/Interface/order";
import errorCode from "../../../utils/http/errorCode";
import { ImgIconRightGray } from "../../../utils/iconMap";
import { jumpPage } from "../../../utils/route/route";
import PopupChooseTime from "./components/PopupChooseTime.vue";
import { couponTypeConfig, couponUseTypeConfig } from "../../../enums/coupon";
import {
  orderSourceType,
  orderStatus,
  orderType,
  payType,
} from "../../../enums/order";
import { useLakalaPay, usePayment, useWechatPay } from "../../../hooks/usePay";
import { useImgSrc } from "../../../hooks/useImg";
import { useSubscribeTemplate } from "../../../hooks/useSubscribe";
import { subscribeEnum } from "../../../enums/subscribe";
import { useGetConfig } from "../../../hooks/useCommon";
import { configKeyEnum } from "../../../enums/common";
import { getServiceDetail } from "../../../api/Interface/service";
import dayjs from "dayjs";

const Instance = getCurrentInstance();
const $vm = Instance?.appContext.config.globalProperties;
const $data = reactive({
  address: "", // 选择的地址
  info: null,
  time: "", // 选择的服务时间
  timeStamp: 0, // 选择的服务时间时间戳
  chooseTimeShow: false, // 选择日期
  message: "",
  buying: false, // 预约中 不可重复预约
  nowDate: dayjs(),
  timer: null,
});
const params = reactive({
  localNo: "",
  //   domesticServiceId: "", // 服务技能id
  userAddressId: "", // 地址ID
  firstStartServicedAt: 0, // 服务时间【十位时间戳】
  remark: "", // 备注
});
const init = async () => {
  $data.timer = setInterval(() => {
    $data.nowDate = dayjs();
  }, 6000 * 10);
  // 选择地址通信
  uni.$on(eventBus.service.address, async (e) => {
    $data.address = e.address;
    params.userAddressId = e.userAddressId;
    console.log("选择地址通信", e);
    await getData();
  });
};
const clearTimer = () => {
  clearInterval($data.timer);
  $data.timer = null;
};
/** 初始化数据 */
const getData = async () => {
  $data.message = "数据加载中...";
  await getOrderDetail({
    orderServiceId: params.localNo,
  }).then((res) => {
    if (res.code === errorCode.success) {
      $data.info = res.data;
      if ($data.info) {
        $data.info._picurl = useImgSrc($data.info.picurl);
        $data.info.addressSnapshot = $data.info.addressSnapshot ?? {};
        params.userAddressId = $data.info.addressSnapshot.userAddressId;
        $data.address = $data.info.addressSnapshot.address;
        // params.domesticServiceId =
        //   $data.info.serviceSnapshot?.domesticServiceId;
        params.firstStartServicedAt = $data.info.firstStartServicedAt;
        params.remark = $data.info.remark;
      }
    }
  });
  $data.message = "";
};
const onCheckAddress = () => {
  jumpPage({
    to: "/package-my/pages/addressManage/index",
    query: {
      fromType: eventBus.service.address,
    },
  });
};
const onChooseTime = (e) => {
  if (!e) return;
  const { time, label } = e;
  $data.timeStamp = time;
  $data.time = label;
  getData();
};
/** 预约 */
const onSave = async () => {
  if ($data.buying) {
    return;
  }
  if (!$data.timeStamp) {
    BasicConfig.toast("您尚未添加服务时间，请添加服务时间后提交订单");
    return;
  }
  if (!params.userAddressId) {
    BasicConfig.toast("您尚未选择服务地址，请选择服务地址后提交订单");
    return;
  }
  const can = uni.canIUse("createOrder");
  console.log("can", can, tt, uni.createOrder);
  if (!can) {
    BasicConfig.toast("当前版本不支持创建订单，请升级到最新版本");
    return;
  }
  $data.buying = true;
  BasicConfig.loadToast("预约中...");
  params.firstStartServicedAt = $data.timeStamp;
  console.log("预约params", params);
  await updateSubscribeOrder(params)
    .then((res) => {
      BasicConfig.toast(res.msg);
      if (res.code === errorCode.success) {
        setTimeout(() => {
          uni.navigateBack({
            delta: 1,
          });
          //   jumpPage({
          //     to: `/package-service/pages/order/order`,
          //     mode: "reLaunch",
          //   });
        }, 1500);
      } else {
        $data.buying = false;
      }
    })
    .catch((_) => {
      uni.hideLoading();
      $data.buying = false;
    });
};
/** 申请退款 */
const onBack = () => {
  uni.navigateBack({
    delta: 1,
  });
};
onLoad((options) => {
  //   params.domesticServiceId = options.id;
  params.localNo = options.localNo;
  $data.buying = false;
  init();
  getData();
});
onReady(() => {});
onUnload(() => {
  // uni.$off(eventBus.service.confirm);
  uni.$off(eventBus.service.address);
  clearTimer();
});
</script>
<style lang="scss" scoped>
.page {
  background: #f7f8fa;
  width: 100vw;
  min-height: 100vh;
  font-size: 32rpx;
  .address {
    background: #ffffff;
    display: flex;
    align-items: center;
    padding: 30rpx;
    &_left {
      width: calc(100% - 16rpx);
      padding-right: 30rpx;
    }
    &_right {
      width: 16rpx;
      height: 30rpx;
      image {
        width: 100%;
        height: 100%;
      }
    }
  }
  .detail {
    background: #ffffff;
    padding: 30rpx;
    display: flex;
    align-items: center;
    margin-top: 30rpx;
    &_img {
      width: 160rpx;
      height: 160rpx;
      image {
        width: 100%;
        height: 100%;
        border-radius: 20rpx;
      }
    }
    &_content {
      width: calc(100% - 160rpx);
      padding-left: 30rpx;
      // display: flex;
      // flex-direction: column;
      // justify-content: space-between;
      height: 100%;
      &--title {
        font-size: 36rpx;
        font-weight: 700;
      }
      &--desc {
        color: #666666;
        font-size: 34rpx;
        margin: 20rpx 0;
      }
      &--price {
        font-size: 34rpx;
        color: $main-color;
      }
    }
  }
  .time {
    padding: 30rpx;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 30rpx;
    &_time {
      font-size: 34rpx;
      color: #333333;
    }
    &_content {
      display: flex;
      align-items: center;
      &--check {
        font-size: 34rpx;
      }
      &--icon {
        width: 16rpx;
        height: 30rpx;
        margin-left: 20rpx;
        image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .coupon {
    padding: 30rpx;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 30rpx;
    &_time {
      font-size: 34rpx;
      color: #333333;
    }
    &_content {
      display: flex;
      align-items: center;
      &--check {
        font-size: 34rpx;
      }
      &--icon {
        width: 16rpx;
        height: 30rpx;
        margin-left: 20rpx;
        image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .foot_box {
    padding: 30rpx;
    z-index: 9;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .bill {
      font-size: 34rpx;
      display: flex;
      align-items: center;
    }
    .btn {
      width: 50%;
      padding: 30rpx;
      border-radius: 100rpx;
      text-align: center;
      font-size: 34rpx;
    }
    .btn_save {
      background: $main-color;
      color: #ffffff;
    }
  }
}
</style>
  